package com.crgp.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import com.crgp.game.client.message.ActionMessage;
import com.crgp.game.client.message.Message;
import com.crgp.server.bean.Client;
import com.crgp.server.util.ByteUtils;

public class Server implements Runnable {
	public static final String SEND = "SEND";
	public static final String RECEIVE = "RECEIVE";

	public static final int PORT = 15000;

	private ServerSocket server;

	private ArrayList<Client> sendClientList = new ArrayList<Client>();
	private ArrayList<Client> receiveClientList = new ArrayList<Client>();

	public Server() {
		try {
			server = new ServerSocket(PORT);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		while (true) {
			try {
				Socket s = server.accept();
				s.setKeepAlive(true);

				InputStream is = s.getInputStream();

				// 读取数据大小
				byte sb[] = new byte[4];
				is.read(sb);
				int size = ByteUtils.byteArrayToInt(sb);
				// 读取数据
				byte b[] = new byte[size];
				is.read(b);
				String cmd = new String(b);

				String UID = cmd.split(":")[1];
				Client client = new Client(UID, s);

				if (cmd.startsWith(SEND)) {
					sendClientList.add(client);

					System.out.println("[SERVER]  :  " + "服务器接收到握手信号 ：SendClient ：" + cmd);
					new Thread(new SendClientProcesser(client)).start();
				} else if (cmd.startsWith(RECEIVE)) {
					receiveClientList.add(client);

					System.out.println("[SERVER]  :  " + "服务器接收到握手信号 ：ReceiveClient ：" + cmd);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	class SendClientProcesser implements Runnable {
		private Client client;

		public SendClientProcesser(Client client) {
			super();
			this.client = client;
		}

		@Override
		public void run() {
			while (true) {
				// 从SendClient中接收到请求消息，
				// 验证消息是否合法,目前只是验证如果发送端和接收端类型相同,则非法.
				// 如果消息非法,不进行转发.
				// 根据targetID，在ReceiveClientList中寻找对应的接收端.
				// 将消息直接转发过去
				try {
					// 读取数据大小
					byte sb[] = new byte[4];
					client.getIS().read(sb);
					int size = ByteUtils.byteArrayToInt(sb);
					// 读取数据
					byte b[] = new byte[1024];
					int len = client.getIS().read(b);
					String cmd = new String(b, 0, len);
					size = size - len;
					while (size > 0) {
						len = client.getIS().read(b);
						cmd = cmd + new String(b, 0, len);
						size = size - len;
					}

					System.out.println("[SERVER]  :  " + "--------------服务器消息处理开始--------------");

					System.out.println("[SERVER]  :  " + "服务器接收到消息 ：(" + size + ")" + cmd);

					ActionMessage message = (ActionMessage) Message.createMessage(cmd);

					if (message.getSourceType().equals(message.getTargetType())) {
						continue;
					}

					Client receiveClient = null;
					for (int i = 0; i < receiveClientList.size(); i++) {
						Client c = receiveClientList.get(i);
						// 找到转发对象
						if (c.getUID().equals(message.getTargetId())) {
							receiveClient = c;
							break;
						}
					}

					if (receiveClient != null) {
						System.out.println("[SERVER]  :  " + "找到转发对象 ：(" + cmd.getBytes().length + ")"
								+ receiveClient.getUID());
						// 转发消息
						receiveClient.getOS().write(ByteUtils.intToByteArray(cmd.getBytes().length));
						receiveClient.getOS().write(cmd.getBytes());
						receiveClient.getOS().flush();

						System.out.println("[SERVER]  :  " + "转发完成 ");
						// 如果有返回值，等待返回数据
						if (message.hasReceipt()) {
							System.out.println("[SERVER]  :  " + "有返回值，等待返回数据");

							// 读取数据大小
							sb = new byte[4];
							receiveClient.getIS().read(sb);
							size = ByteUtils.byteArrayToInt(sb);
							// 读取数据
							b = new byte[1024];
							len = receiveClient.getIS().read(b);
							cmd = new String(b, 0, len);
							size = size - len;
							while (size > 0) {
								len = receiveClient.getIS().read(b);
								cmd = cmd + new String(b, 0, len);
								size = size - len;
							}

							System.out.println("[SERVER]  :  " + "收到返回数据 ：(" + size + ")" + cmd);
							// 将返回至发送回去
							client.getOS().write(ByteUtils.intToByteArray(cmd.getBytes().length));
							client.getOS().write(cmd.getBytes());
							client.getOS().flush();
							System.out.println("[SERVER]  :  " + "发送返回数据成功");
						}
					} else {
						System.out.println("[SERVER]  :  " + "没有找到转发对象 ：(" + cmd.getBytes().length + ")"
								+ message.getTargetId());
					}
					System.out.println("[SERVER]  :  " + "--------------服务器消息处理结束--------------");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
